package org.example.serializer;/**
 * @Description: TODO
 * @Author: sats@jz
 * @Date: 2024/12/24 19:36
 **/

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

import java.io.IOException;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年12月24日 19:36
 */
public class JacksonSerializer implements Serializer{
    private final ObjectMapper objectMapper = new ObjectMapper()
            .activateDefaultTyping(
                    LaissezFaireSubTypeValidator.instance,
                    ObjectMapper.DefaultTyping.NON_FINAL,
                    JsonTypeInfo.As.PROPERTY
            );
    @Override
    public <T> byte[] serialize(T object) throws IOException {
        try {
            return objectMapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e){
            throw new IOException("序列化失败", e);
        }
    }
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        try{
            return objectMapper.readValue(data, clazz);
        } catch (JsonProcessingException e){
            throw new IOException("反序列化失败", e);
        }
    }
}
